import os
from xml.dom.minidom import parse

import openpyxl

"""
根据key和语言缩写合入对应的语言string.xml文件
"""

excel_dir = 'res/new_excel/'
string_dir = 'res/origin/'
languages_map = {'ar': 'ar', 'cs': 'cs', 'da': 'da', 'de': 'de', 'el': 'el',
                 'es': 'es', 'fi': 'fi', 'fr': 'fr', 'fr-ca': 'fr-rCA', 'hu': 'hu',
                 'it': 'it', 'iw': 'iw', 'ja': 'ja', 'ko': 'ko', 'nl': 'nl',
                 'no-no': 'nb', 'pl': 'pl', 'pt': 'pt', 'pt-br': 'pt-rBR', 'ro': 'ro',
                 'ru': 'ru', 'sk': 'sk', 'sv': 'sv', 'th': 'th', 'zh-cn': 'zh',
                 'zh-tw': 'zh-rTW'}


def write_to_string_file(path, str_dict):
    """
    将字符串字典写入string文件
    :param path: string文件路径
    :param str_dict: 字符串字典
    :return:
    """
    print('merge to ' + path, str_dict)
    dom = parse(path)
    name_list = []
    for node in dom.getElementsByTagName('string'):
        name = node.getAttribute('name')
        name_list.append(name)

    for key in str_dict.keys():
        if key not in name_list:
            # 不包含对应key，则添加新的string标签
            str_element = dom.createElement("string")
            str_element.setAttribute('name', key)
            text_node = dom.createTextNode(str_dict[key])
            str_element.appendChild(text_node)
            res_element = dom.getElementsByTagName("resources")[0]
            res_element.appendChild(str_element)
        else:
            # 包含对应key, 查找并修改
            str_element = dom.createElement("string")
            str_element.setAttribute('name', key)
            text_node = dom.createTextNode(str_dict[key])
            str_element.appendChild(text_node)
            old_node = None
            for node in dom.getElementsByTagName('string'):
                name = node.getAttribute('name')
                if name == key:
                    old_node = node
            res_element = dom.getElementsByTagName("resources")[0]
            res_element.removeChild(old_node)
            res_element.appendChild(str_element)

    # 去除空行
    dom_str = "".join([line for line in dom.toprettyxml().splitlines(True) if line.strip()])
    # 修改后的dom写入文件
    with open(path, 'w') as fh:
        fh.write(dom_str)


def get_target_string_file(file):
    """
    根据excel文件名中的语言缩写，返回目标strings.xml的文件路径
    """
    start = file.index('Translation') + len('Translation') + 1
    end = file.rindex('_')
    excel_lan = file[start:end].lower()
    if excel_lan in languages_map.keys():
        lan = languages_map[excel_lan]
        return string_dir + 'values-' + lan + '/strings.xml'
    else:
        return ''


def merge_to_string_file(excel_file):
    # 目标字符串xml
    string_file = get_target_string_file(excel_file)
    if string_file == '':
        print('no target string file, excel is', excel_file)
        return

    wb = openpyxl.load_workbook(excel_file)
    # 第一个Sheet页
    ws = wb[wb.sheetnames[0]]
    for index, col_data in enumerate(ws.columns):
        if index < 2:
            continue
        str_dict = {}

        # 将列以key,value形式写入str_dict
        for row_index, cell in enumerate(col_data):
            if row_index == 0:
                continue
            key = ws.cell(row_index + 1, 1).value
            if key is None or cell.value is None:
                continue
            str_dict[key] = cell.value
        if len(str_dict) == 0:
            continue
        write_to_string_file(string_file, str_dict)
    wb.close()


def main():
    files = os.listdir(excel_dir)
    for file in files:
        excel_path = excel_dir + file
        merge_to_string_file(excel_path)


if __name__ == '__main__':
    main()
